package com.example.redissiondemo;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author chaird
 * @create 2022-10-30 20:26
 */
@RestController
public class DistributedLockController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private Redisson redisson;


    @RequestMapping("/reduce_stock")
    public String reduceStock() {

        //key的名称
        String lockKey = "lock";

        RLock lock = redisson.getLock(lockKey);

        lock.lock();
        try {
//            //查数据库（redis）中库存数量
//            Integer stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
//            //判断库存
//            if (stock > 0) {
//                System.out.println("消费库存成功--->" + stock);
//                //更新库存
//                stock = stock - 1;
//                stringRedisTemplate.opsForValue().set("stock", String.valueOf(stock));
//            } else {
//                System.out.println("消费库存失败。。。");
//            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


        return "helloworld";
    }


}
